package com.easonji.admin.manager.impl;

import java.util.List;

import javax.annotation.Resource;

import com.easonji.admin.dao.RoleDAO;
import com.easonji.admin.mapper.RoleMapper;
import com.easonji.admin.model.Role;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.easonji.admin.manager.RoleManager;
import com.easonji.common.constant.Consts;
import com.easonji.common.constant.cache.CacheConsts;
import com.easonji.common.constant.cache.CacheKeyConsts;
import com.easonji.common.util.StringUtils;

/**
 * @ClassName: RoleManagerImpl
 * @Description: 角色通用类实现
 * @Author: LiuJun
 * @date: 2018/07/29 07:48
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
@Service
public class RoleManagerImpl implements RoleManager {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleDAO roleDAO;

    @Override
    @Cacheable(value = CacheConsts.CONSTS, key = "'" + CacheKeyConsts.ROLE_NAME + "'+#roleId")
    public String getRoleNameById(Integer roleId) {
        String result = "";
        Wrapper<Role> wrapper = new EntityWrapper<>();
        wrapper.eq("id", roleId);
        List<Role> roles = roleMapper.selectList(wrapper);
        if (StringUtils.isNotEmpty(roles)) {
            result = roles.get(0).getName();
        }
        return result;
    }

    @Override
    @Cacheable(value = CacheConsts.CONSTS, key = "'" + CacheKeyConsts.ROLE_NAMES + "'+#roleIds")
    public String getRoleNamesByIds(String roleIds) {
        StringBuilder result = new StringBuilder();
        Wrapper<Role> wrapper = new EntityWrapper<>();
        String[] ids = StringUtils.split(roleIds, Consts.COMMA);
        wrapper.in("id", ids);
        List<Role> roles = roleMapper.selectList(wrapper);
        if (StringUtils.isEmpty(roles)) {
            return "";
        } else {
            roles.forEach(role -> {
                result.append(",");
                result.append(this.getAppNameById(role.getId()) + Consts.HYPHEN + role.getName());
            });
            return result.substring(1);
        }
    }

    @Override
    @Cacheable(value = CacheConsts.CONSTS, key = "'" + CacheKeyConsts.ROLE_APP_ID + "'+#roleId")
    public Integer getAppIdById(Integer roleId) {
        Wrapper<Role> wrapper = new EntityWrapper<>();
        wrapper.eq("id", roleId);
        List<Role> roles = roleMapper.selectList(wrapper);
        if (StringUtils.isEmpty(roles)) {
            return null;
        }
        return roles.get(0).getAppId();
    }

    @Override
    @Cacheable(value = CacheConsts.CONSTS, key = "'" + CacheKeyConsts.ROLE_APP_NAME + "'+#roleId")
    public String getAppNameById(Integer roleId) {
        return roleDAO.selectAppNameById(roleId);
    }
}
